#include "log.h"

mozhu::log* mozhu::log::m_instance = nullptr;

mozhu::log* mozhu::log::Get()
{
    static std::once_flag once;
    std::call_once(once, [&]() { m_instance = new log; });
    return m_instance;
}

void mozhu::log::writelog(int type, std::string info)
{
    log* ptr = Get();
    logdata middle;
    middle.info = info;
    middle.type = type;
    middle.timestamp = gettime();
    ptr->data.emplace_back(middle);
}

std::vector<logdata> mozhu::log::getlog()
{
    std::vector<logdata> middle;
    middle = Get()->data;
    return middle;
}

void mozhu::log::loaddatabase(std::string location)
{
    mozhu::log* ptr = Get();
    std::fstream database(location);
    if(!database.is_open())
        return;
    ptr->databaselocation = location;
    int number = 0;
    database >> number;
    for(int i = 0;i<number;i++)
    {
        logdata middle;
        database >> middle.type;
        database >> middle.timestamp.year;
        database >> middle.timestamp.month;
        database >> middle.timestamp.date;
        database >> middle.timestamp.hour;
        database >> middle.timestamp.minute;
        database >> middle.timestamp.sec;
        database >> middle.info;
        Get()->data.emplace_back(middle);
    }
}

void mozhu::log::unloaddatabase()
{
    mozhu::log* ptr = Get();
    if(ptr->databaselocation.empty())
        return;
    std::fstream database(ptr->databaselocation);
    database << ptr->data.size() << "\n";
    for(logdata middle : ptr->data)
    {
        database << middle.type << " ";
        database << middle.timestamp.year << " ";
        database << middle.timestamp.month << " ";
        database << middle.timestamp.date << " ";
        database << middle.timestamp.hour << " ";
        database << middle.timestamp.minute << " ";
        database << middle.timestamp.sec << " ";
        database << middle.info << "\n";
    }
}